package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.modular.system.controller.dto.TApplicationTask;
import cn.stylefeng.guns.modular.system.controller.dto.ZapplicationTask;
import cn.stylefeng.guns.modular.system.entity.IndentOrder;
import cn.stylefeng.guns.modular.system.entity.TApplication;
import cn.stylefeng.guns.modular.system.entity.TApplicationAudit;
import cn.stylefeng.guns.modular.system.mapper.TApplicationMapper;
import cn.stylefeng.guns.modular.system.mapper.YtypeMapper;
import cn.stylefeng.guns.modular.system.model.params.TApplicationAuditParam;
import cn.stylefeng.guns.modular.system.model.params.TApplicationParam;
import cn.stylefeng.guns.modular.system.service.IndentOrderService;
import cn.stylefeng.guns.modular.system.service.SysDictService;
import cn.stylefeng.guns.modular.system.service.TApplicationAuditService;
import cn.stylefeng.guns.modular.system.service.TApplicationService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.ResponseMsg;
import cn.stylefeng.guns.sys.core.util.common.SystemConstant;
import cn.stylefeng.guns.sys.core.util.common.UploadFileUtils;
import cn.stylefeng.guns.sys.core.util.common.UploadResult;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.util.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 控制器
 *  退款申请
 * @author yl
 * @Date 2019-07-09 20:39:18
 */
@Controller
@RequestMapping("/tApplication")
public class TApplicationController extends BaseController {

    private String PREFIX = "/tApplication";

    @Autowired
    private TApplicationService tApplicationService;

    @Autowired
    private YtypeMapper ytypeMapper;

    @Autowired
    private TApplicationMapper tApplicationMapper;

    //订货单servlec
    @Autowired
    private IndentOrderService indentOrderService;

    //字典管理
    @Autowired
    private SysDictService sysDictService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private IdentityService identityService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private TApplicationAuditService tApplicationAuditService;



    /**
     * 跳转到主页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/tApplication.html";
    }

    /**
     * 新增页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/add")
    public String add(Model modle) {
        //select 下拉框查询订货单编号
        modle.addAttribute("indent_order_num",indentOrderService.list());

        //下拉查询字典管理的数据
        modle.addAttribute("dict_name",sysDictService.list());
        modle.addAttribute("username",ShiroKit.getUserNotNull().getName());
        modle.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/tApplication_add.html";
    }

    /**
     * 编辑页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        //select 下拉框查询订货单编号
        model.addAttribute("indent_order_num",indentOrderService.list());

        //下拉查询字典管理的数据
        model.addAttribute("dict_name",sysDictService.list());
        return PREFIX + "/tApplication_edit.html";
    }

    @RequestMapping("/getBack")
    public String getBack() {
        return PREFIX + "/tApplicationCheck.html";
    }

    /**
     * 新增接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TApplicationParam tApplicationParam) throws ParseException {
        //获取当前系统时间
        Date currDate = (Date) Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(currDate); //String类型
        Date date = sdf.parse(dateTime);        //Date类型
        tApplicationParam.setDate(date);
        //存储图片
        tApplicationParam.setEnclosu(SystemConstant.TENCENT_URL+tApplicationParam.getEnclosu());

        tApplicationParam.setApplicantId(ShiroKit.getUserNotNull().getId());
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() +"");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.pc_tuikuan);
        tApplicationParam.setProcessInstanceId(processInstance.getId());
        tApplicationService.add(tApplicationParam);

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() +"");
        taskService.complete(task.getId());
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author yl
     * @Date 2019-07-09
     *
     * 修改数据接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TApplicationParam tApplicationParam) {

        tApplicationParam.setType(tApplicationParam.getType());
        tApplicationParam.setRemoney(tApplicationParam.getRemoney());
        //修改图片
        tApplicationParam.setEnclosu(SystemConstant.TENCENT_URL+tApplicationParam.getEnclosu());

        tApplicationParam.setOrderId(tApplicationParam.getOrderId());
        tApplicationParam.setRemarks(tApplicationParam.getRemarks());
        tApplicationParam.setId(tApplicationParam.getId());
        String a = tApplicationService.UpdateApplicationId(tApplicationParam.getType(),tApplicationParam.getRemoney(),tApplicationParam.getEnclosu(),tApplicationParam.getOrderId(),tApplicationParam.getRemarks(),tApplicationParam.getId());
        //this.tApplicationService.update(tApplicationParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TApplicationParam tApplicationParam) {
        this.tApplicationService.delete(tApplicationParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(String id) {
        TApplication detail = tApplicationService.QueryId(id);
        return ResponseData.success(detail);
    }


    /**
     *退款表关联订单表连接查询
     * 根据订单编号查询
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo QueryListLiftJoin(Model model, String condition) {

        List<TApplication> list = tApplicationService.QueryListLiftJoin(condition);
        model.addAttribute("list",list);
        LayuiPageInfo lay = new LayuiPageInfo();
        lay.setData(list);
        return lay;
    }
    @ResponseBody
    @RequestMapping("/checkList")
    public LayuiPageInfo checkList(){

        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(SystemConstant.pc_tuikuan).taskCandidateUser(ShiroKit.getUserNotNull().getId() +"").list();

        if (tasks.size() == 0){
            return  new LayuiPageInfo();
        }
        List<TApplicationTask> tApplicationTasks = tasks.stream().filter(task -> tApplicationService.getByProcessInstanceId(task.getProcessInstanceId())!=null).map(task -> {
            TApplicationTask tApplicationTask = new TApplicationTask();

            BeanUtils.copyProperties(indentOrderService.getByProcessInstanceId(task.getProcessInstanceId()), tApplicationTask);
            tApplicationTask.setUserName(userService.getById(tApplicationService.getByProcessInstanceId(task.getProcessInstanceId()).getApplicantId()).getName());
            tApplicationTask.setDeptName(deptService.getById(userService.getById(tApplicationService.getByProcessInstanceId(task.getProcessInstanceId()).getApplicantId()).getDeptId()).getSimpleName());
            tApplicationTask.setProcessInstanceId(task.getProcessInstanceId());
            tApplicationTask.setTaskId(task.getId());
            tApplicationTask.setIndentOrderNum(indentOrderService.getById(tApplicationService.getByProcessInstanceId(task.getProcessInstanceId())).getIndentOrderNum());
            String status = null;
            if (StatusCode.PENDING.getVal() == tApplicationService.getByProcessInstanceId(task.getProcessInstanceId()).getTStatus()){
                status = "待审核";
            } else if (StatusCode.SUCCESS.getVal()==tApplicationService.getByProcessInstanceId(task.getProcessInstanceId()).getTStatus()){
                status = "审核成功";
            }
            tApplicationTask.setStatus(status);
            return tApplicationTask;
        }).collect(Collectors.toList());

        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(tApplicationTasks);
        layuiPageInfo.setCount(tApplicationTasks.size());
        return  layuiPageInfo;
    }


    @ResponseBody
    @RequestMapping("/check")
    public ResponseData check(TApplicationAuditParam tApplicationAuditParam){
        TApplicationAudit tApplicationAudit = new TApplicationAudit();
        BeanUtils.copyProperties(tApplicationAuditParam,tApplicationAudit);
        tApplicationAudit.setAuditTime(new Date());
        tApplicationAudit.setUserId(ShiroKit.getUserNotNull().getId());

        Task task = taskService.createTaskQuery().taskId(tApplicationAuditParam.getTaskId()).singleResult();
        tApplicationAudit.setProcessInstanceId(task.getProcessInstanceId());
        tApplicationAudit.setTaskId(task.getId());
        tApplicationAuditService.save(tApplicationAudit);

        Map<String,Object> map = new HashMap<>();
        map.put("status",tApplicationAuditParam.getAuditStatus());
        taskService.complete(task.getId(),map);
     return  ResponseData.success();
    }

    /*---------------------上传接口------------------------------------------*/
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public ResponseData uploadUtils(@RequestPart("file") MultipartFile file) throws FileNotFoundException {

        if (ToolUtil.isEmpty(file)){
            return  ResponseData.error(201,"上传失败，图片为空");
        }else{

            ResponseMsg msg = UploadFileUtils.uploadFile(file);

            if (msg.getStatus() == 10001){
                UploadResult result = (UploadResult) msg.getResult();
                return  ResponseData.success(200,"上传成功",result.getPath());
            }else {
                return  ResponseData.error(202,"上传失败，图片格式错误");
            }

        }

    }


    /*
    * 查询所有订货单
    * */
    @RequestMapping("/inder")
    public ResponseData listindentOrder(){
        Page<List<IndentOrder>> listPage = tApplicationMapper.listindentOrder(ShiroKit.getUserNotNull().getId());
        return  new ResponseData().success(listPage);
    }

    @RequestMapping("/orderDetail")
    public String indentOrderDetail(Model model,Long id, String taskId){


        //经销商登录名
        ShiroUser shiroUser =  ShiroKit.getUserNotNull();
        model.addAttribute("username",shiroUser.getName());

        //部门
        String deptName = deptService.getById(shiroUser.getDeptId()).getSimpleName();
        model.addAttribute("deptName",deptName);
//        IndentOrderCheck indentOrderCheck = indentOrderCheckService.getById(id);
//        Long indentId = indentOrderCheck.getIndetOrderId();
//        IndentOrder indentOrder = indentOrderService.getById(id);
//        String ids = indentOrder.getPurchaseId();
//        model.addAttribute("ids",ids);
        model.addAttribute("id",id);
        model.addAttribute("taskId", taskId);
        return  PREFIX + "/tApplicationCheckDetail.html";
    }

    /**
     * 查询详情
     * @param id
     * @return
     */
    @RequestMapping("/getDetail")
    @ResponseBody
    public LayuiPageInfo getDetail(Long id) {
        Page page = LayuiPageFactory.defaultPage();
        IPage iPage = tApplicationMapper.getDetailById(page, id);
//        BeanUtils.copyProperties(bothSaleCommit, bothSaleCommitParam);
//        bothSaleCommitParam.setUserName(userService.getById(bothSaleCommit.getUserId()).getName());
        return LayuiPageFactory.createPageInfo(iPage);
    }

    /**
     * 跳转到审核页面
     * @return
     */
    @RequestMapping("/shenheIndex")
    public String shenheIndex(String taskId,Long indentOrderId){
        super.setAttr("taskId",taskId);
        super.setAttr("indentOrderId",indentOrderId);
        return  PREFIX + "/check.html";
    }

}


